﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace _081.异常筛选器
{
    public class MyExceptionFilter : IAsyncExceptionFilter
    {

        private readonly IWebHostEnvironment webHost;

        public MyExceptionFilter(IWebHostEnvironment webHost)
        {
            this.webHost = webHost;
        }
        public Task OnExceptionAsync(ExceptionContext context)
        {
            // context.Exception 代表异常信息对象
            // 如果给context.ExceptionHandled = true;则其他ExceptionFilter不会再执行
            // context.Result的值会被输出给客户端
            string message = string.Empty;

            if (webHost.IsDevelopment())
            {
                // 如果是开发环境 给异常学习
                message = context.Exception.ToString();
            }
            else
            {
                message = "服务器发生未处理异常";
            }
            ObjectResult objectResult = new ObjectResult(new {code = 500,message = message});

            context.Result = objectResult;
            context.ExceptionHandled = true;
            context.Result = objectResult;

            return Task.CompletedTask;
        }
    }
}
